package com.huangmingfu.builder;

import java.net.URI;
import java.net.URISyntaxException;

/**
 * @Author: 黄名富
 * @Description:
 */
public class JdbcConnectorBuilder {

    private String scheme;
    private String host;
    private String port;
    private String database;
    private String username;
    private String password;

    public JdbcConnectorBuilder setScheme(String scheme) {
        this.scheme = scheme;
        return this;
    }

    public JdbcConnectorBuilder setHost(String host) {
        this.host = host;
        return this;
    }

    public JdbcConnectorBuilder setPort(String port) {
        this.port = port;
        return this;
    }

    public JdbcConnectorBuilder setDatabase(String database) {
        this.database = database;
        return this;
    }

    public JdbcConnectorBuilder setUsername(String username) {
        this.username = username;
        return this;
    }

    public JdbcConnectorBuilder setPassword(String password) {
        this.password = password;
        return this;
    }

    /**
     * 产品
     */
    private JdbcConnector jdbcConnector = null;

    public JdbcConnectorBuilder() {
        jdbcConnector = new JdbcConnector();
    }

    public JdbcConnector build() {
        StringBuilder sb = new StringBuilder("jdbc:");
        sb.append(scheme == null ? "mysql" : scheme).append("://");
        if (host == null) throw new RuntimeException("host不能为空");
        sb.append(host);
        sb.append(":").append(port == null ? "3306" : port);
        if (database == null) throw new RuntimeException("数据库不能为空");
        sb.append("/").append(database);
        try {
            URI uri = new URI(sb.toString());
            if (username == null || password == null) throw new RuntimeException("账号或密码错误");
            jdbcConnector.initConnection(uri);
        } catch (URISyntaxException e) {
            throw new RuntimeException("连接失败，连接信息有误");
        }
        return jdbcConnector;
    }

}
